

package ro.ase.catalog;

import java.io.PrintStream;
import java.io.PrintWriter;


/**
 *
 * <p>
 * 
 */
public abstract class CatalogException extends Exception {

    private final Throwable cause;


    /**
     * Construct emtpy exception object.
     */
    public CatalogException() {
        super();
        cause = null;
    }
    
    
    /**
     * Construct CatalogException with message string.
     * @param s Error message string.
     */
    public CatalogException(String s) {
        super(s);
        cause = null;
    }
    
    
    /**
     * Construct CatalogException, wrapping existing throwable.
     * @param s Error message
     * @param t Existing connection to wrap.
     */
    public CatalogException(String s, Throwable t) {
        super(s);
        cause = t;
    }
    
    
    /**
     * Construct CatalogException, wrapping existing throwable.
     * @param t Existing exception to be wrapped.
     */
    public CatalogException(Throwable t) {
        cause = t;
    }
    
    
    /**
     * Get root cause object, or null if none.
     * @return Root cause or null if none.
     */
    public Throwable getRootCause() {
        return cause;
    }
    
    
    /**
     * Get root cause message.
     * @return Root cause message.
     */
    public String getRootCauseMessage() {
        String message = null;
        if (getRootCause()!=null) {
            if (getRootCause().getCause()!=null) {
                message = getRootCause().getCause().getMessage();
            }
            message = (message == null) ? getRootCause().getMessage() : message;
            message = (message == null) ? super.getMessage() : message;
            message = (message == null) ? "NONE" : message;
        }
        return message;
    }
    
    
    /**
     * Print stack trace for exception and for root cause exception if htere is one.
     * @see java.lang.Throwable#printStackTrace()
     */
    public void printStackTrace() {
        super.printStackTrace();
        if (cause != null) {
            System.out.println("--- ROOT CAUSE ---");
            cause.printStackTrace();
        }
    }
    
    
    /**
     * Print stack trace for exception and for root cause exception if htere is one.
     * @param s Stream to print to.
     */
    public void printStackTrace(PrintStream s) {
        super.printStackTrace(s);
        if (cause != null) {
            s.println("--- ROOT CAUSE ---");
            cause.printStackTrace(s);
        }
    }
    
    
    /**
     * Print stack trace for exception and for root cause exception if htere is one.
     * @param s Writer to write to.
     */
    public void printStackTrace(PrintWriter s) {
        super.printStackTrace(s);
        if (null != cause) {
            s.println("--- ROOT CAUSE ---");
            cause.printStackTrace(s);
        }
    }
    
}
